package com.lagou.rpc.server.zookeeper;

import com.alibaba.fastjson.JSONObject;
import com.lagou.rpc.common.SimpleRpcConstants;
import com.lagou.rpc.common.entity.HostPortMetaData;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 响应时间刷新定时调度任务
 *
 * @author wlz
 * @date 2020/5/22
 */
public class RefreshResponseTimeScheduler {
    private static final Logger logger = LoggerFactory.getLogger(RefreshResponseTimeScheduler.class);

    private volatile long lastResponseTime;
    private volatile long currentResponseTime = lastResponseTime;
    private HostPortMetaData hostPortMetaData;
    private String name;
    private CuratorFramework client;

    public RefreshResponseTimeScheduler(HostPortMetaData hostPortMetaData, String name, CuratorFramework client) {
        this.hostPortMetaData = hostPortMetaData;
        this.name = name;
        this.client = client;
    }

    public void startRefreshTask(int secs) {
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
        scheduledThreadPoolExecutor.scheduleAtFixedRate(this::doRefresh, 0, secs, TimeUnit.SECONDS);
    }

    private void doRefresh() {
        if (lastResponseTime != currentResponseTime) {
            hostPortMetaData.setLastResponseCostTime(currentResponseTime);
        } else {
            hostPortMetaData.setLastResponseCostTime(0L);
        }
        try {
            client.setData().forPath(SimpleRpcConstants.SERVER_HOST_LIST_NODE + "/" + name, JSONObject.toJSONBytes(hostPortMetaData));
        } catch (Exception e) {
            logger.error("服务端更新响应时间失败", e);
        }
    }

    public void refresh(long responseTime) {
        lastResponseTime = currentResponseTime;
        currentResponseTime = responseTime;
    }

}
